﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UIShare;
using EFong.View.Proxy;
using System.IO;
using System.Xml.Linq;

namespace EFong.View.Data
{
    public partial class Frm_DataImport : BasicForm
    {
        private BaseServiceProxy _proxy;

        public Frm_DataImport()
        {
            InitializeComponent();
        }

        protected override void InitFields()
        {
            base.InitFields();

            _proxy = BaseServiceProxy.GetInstance();
        }

        protected override void Events()
        {
            base.Events();

            this.btn_Cancel.Click += (s, e) =>
                {
                    this.Close();
                };
            this.btn_Select.Click += (s, e) =>
                {
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter = "XML文件(*.xml)|*.xml";
                    DialogResult result = openFileDialog.ShowDialog();
                    if (result != DialogResult.OK)
                        return;

                    FileName = openFileDialog.FileName;
                    txt_Path.SetText(FileName);
                };
            this.btn_Import.Click += (s, e) =>
                {
                    UIOperManager.SaveData(() => { return true; },
                                       () =>
                                       {
                                           if (FileName == null || FileName == string.Empty)
                                               return false;

                                           try
                                           {
                                               using (TextReader reader = new StreamReader(FileName))
                                               {
                                                   XElement xElement = XElement.Load(reader);
                                                   return _proxy.ImportData(xElement).IsSuccess;
                                               }
                                           }
                                           catch (Exception ex) 
                                           {
                                               MessageBox.Show(ex.Message);
                                               return false;
                                           }
                                       },
                                       "导入成功.",
                                       () =>
                                       {
                                           this.Close();
                                       });
                };
        }

        public string FileName { get; set; }
    }
}
